/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package im.eventservice;

import im.general.AbstractListenBehaviour;
import im.general.Config;
import jade.core.AID;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import java.util.Enumeration;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Gnaskky
 */
public class ClusterShrinkNotifyBehaviour extends AbstractListenBehaviour {

    private EventServiceAgent es;

    ClusterShrinkNotifyBehaviour(EventServiceAgent es) throws Exception {
        this.es = es;
        ACLMessage wrap_msg = new ACLMessage( ACLMessage.INFORM );
        wrap_msg.addUserDefinedParameter( Config.IM_MSG_TYPE, Config.CH_SHRINK_NOTIFY_MSG );
        this.mt = MessageTemplate.MatchCustom(wrap_msg, true );
    }

    @Override
    protected void handleMessage(ACLMessage in_msg) {
        try {

            //MobileNodeInfo mn_info = (MobileNodeInfo) in_msg.getContentObject();
            String shr_ch = in_msg.getSender().getLocalName();

            Vector<String> ch_v = (Vector<String>) in_msg.getContentObject();

            if( Config.TRACE_LVL > Config.ULTRA_TR_LVL )
                System.out.println("[ClusterShrinkNotify]\tCH_SHRINK_NOTIFY_MSG (" + ch_v.size() + ")\t " + shr_ch );

            //System.out.println("SHR.......\n" + ch_v.toString() + "\n......");

            // checks if CH is really in the CH_list
            if( es.heads.containsKey(shr_ch) ) {

                es.removeHead(shr_ch);
                
                // checks if the cluster is not empty
                if( ch_v.size() > 0 ) {
                    //if so advertises all nodes
                    // note use piggybacking :)
                   
                    Enumeration<String> ch_nodes = ch_v.elements();

                    ACLMessage shrnk_msg = new ACLMessage(ACLMessage.CFP);
                    shrnk_msg.addUserDefinedParameter(Config.IM_MSG_TYPE, Config.SHRINK_NOTIFY_MSG );

                    //Vector<String> chl = ;
                    shrnk_msg.setContentObject(es.getCHList());

                    while( ch_nodes.hasMoreElements() )
                        shrnk_msg.addReceiver(new AID(ch_nodes.nextElement(), AID.ISGUID));
            
                    es.sendMessage(shrnk_msg);
                }
            }

        } catch (Exception ex) {
            Logger.getLogger(ClusterJoinNotifyBehaviour.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
    }


}